package com.dhy.replugin

import android.content.Context
import com.qihoo360.replugin.PluginDexClassLoader
import com.qihoo360.replugin.RePluginCallbacks
import com.qihoo360.replugin.RePluginClassLoader
import com.qihoo360.replugin.model.PluginInfo

class ShareClassRePluginCallbacks(context: Context) : RePluginCallbacks(context) {
    private lateinit var hostClassLoader: RePluginClassLoader
    private val shareLibClasses: Array<IShareLibClass> = arrayOf(
        FrescoShareClass(),
        AppShareClass()
    )

    override fun createClassLoader(parent: ClassLoader?, original: ClassLoader?): RePluginClassLoader {
        hostClassLoader = super.createClassLoader(parent, original)
        return hostClassLoader
    }

    override fun createPluginClassLoader(pi: PluginInfo, dexPath: String, optimizedDirectory: String, librarySearchPath: String, parent: ClassLoader): PluginDexClassLoader {
        return ShareClassPluginDexLoader(pi, dexPath, optimizedDirectory, librarySearchPath, parent)
    }

    private inner class ShareClassPluginDexLoader(pi: PluginInfo, dexPath: String, optimizedDirectory: String, librarySearchPath: String, parent: ClassLoader) : PluginDexClassLoader(pi, dexPath, optimizedDirectory, librarySearchPath, parent) {
        private val superLoadClass: (String) -> Class<*> = { name: String ->
            super.loadClass(name)
        }

        override fun loadClass(name: String): Class<*> {
            for (shareLibClass in shareLibClasses) {
                val cls = shareLibClass.loadClass(hostClassLoader, superLoadClass, name)
                if (cls != null) return cls
            }
            return super.loadClass(name)
        }
    }
}

interface IShareLibClass {
    /**
     * 处理特定库中类的共享情况：已处理则返回类，否则返回null
     * */
    fun loadClass(hostClassLoader: RePluginClassLoader, superLoadClass: (String) -> Class<*>, name: String): Class<*>?
}